﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Aspire
{
    /// <summary>
    /// 应用程序内部框架
    /// </summary>
    public class AspireFramework
    {
        public static readonly AspireFramework Instance = new AspireFramework();
        #region Events
        /// <summary>
        /// 内部框架初始化完毕
        /// </summary>
        public event EventHandler Inited;
        /// <summary>
        /// 内部框架初始化失败
        /// </summary>
        public event EventHandler InitFaild;
        #endregion

        /// <summary>
        /// 配置文件完整URL地址。通过服务获取
        /// </summary>
        public string ConfigUri { get; set; }

        /// <summary>
        /// 导航窗口
        /// </summary>
        public Frame Frame { get; set; }

        /// <summary>
        /// 初始化应用程序框架
        /// </summary>
        public void Init()
        {
            if (String.IsNullOrEmpty(ConfigUri)) throw new ArgumentException("未设置ConfigUri");

            Uri cfgFileUri = null;
            try
            {
                cfgFileUri = new Uri(ConfigUri, UriKind.Absolute);
            }
            catch (Exception ex) { }

            if(cfgFileUri == null) throw new ArgumentException("ConfigUri不是有效的Uri");

            WebClient client = new WebClient();
            client.DownloadStringCompleted += ((s1, a1) =>
            {
                if(a1.Error !=null)
                {
                    throw new AspireException(ExceptionType.CONFIG_FILE_ERROR,  "配置文件获取错误", a1.Error);
                }
                if(String.IsNullOrEmpty(a1.Result))
                {
                    throw new AspireException(ExceptionType.CONFIG_FILE_ERROR, "配置文件获取错误, 返回配置文件为空");
                }

                AspireConfig cfg = new AspireConfig();

                try
                {
                    cfg.Load(a1.Result);
                }
                catch (Exception ex)
                {
                    throw new AspireException(ExceptionType.CONFIG_FILE_ERROR, String.Format("配置文件格式错误，无法正常解析。请检查配置文件格式是否正确。配置文件内容：[{0}]", ex));
                }

                this.System = cfg.System;
                if (this.Inited != null) this.Inited.Invoke(this, new EventArgs());

            });
            client.DownloadStringAsync(new Uri(ConfigUri, UriKind.RelativeOrAbsolute));

        }

        public BusinessSystem System { get; set; }
        
    }
}
